package com.softtown.modules.message.service.impl;

import com.softtown.common.constant.Constant;
import com.softtown.common.enums.*;
import com.softtown.common.exception.ErrorCode;
import com.softtown.common.exception.RenException;
import com.softtown.modules.message.email.EmailUtils;
import com.softtown.modules.message.entity.SysEmailContentEntity;
import com.softtown.modules.message.service.SysEmailContentService;
import com.softtown.modules.message.service.SysEmailService;
import com.softtown.modules.sys.dto.AppealDTO;
import com.softtown.modules.sys.entity.SysMsgSendWayEntity;
import com.softtown.modules.sys.service.SysMsgSendWayService;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import static com.softtown.common.utils.VerCodeGenerateUtil.generateVerCode;

/**
 * @version v1.0
 * @ProjectName: softtown-aioffice
 * @ClassName: EmailServiceImpl
 * @Description: 邮箱Service实现层
 * @Author: fuming
 * @Date: 2019/7/12 15:47
 */
@Service
public class SysEmailServiceImpl implements SysEmailService {

    @Resource
    private SysEmailContentService sysEmailContentService;

    @Resource
    private SysMsgSendWayService sysMsgSendWayService;

    @Resource
    private EmailUtils emailUtils;

    /**
     * @param @param [receiver, verCode]
     * @return @return void
     * @throws
     * @Title: sendEmailVerCode
     * @Description: 发送邮箱验证码Service实现方法
     * @author Dingyayong
     * @date 2019/7/12 19:09
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendEmailVerCode(String receiver) {
        boolean f = false;
        String emailCode = generateVerCode();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 获取消息发送的方并填入值
        SysMsgSendWayEntity sysMsgSendWayEntity = sysMsgSendWayService.selectBySendTypeAndType(MsgSendWayTypeEnum.
                MAIL.value(), MsgTypeEnum.EMAIL_FAST_CODE.value());
        Object[] titleArray = new Object[]{SystemNameEnum.SYS_NAME_CN.value()};
        String title = MessageFormat.format(sysMsgSendWayEntity.getMsgTemplateTitle(), titleArray);
        Object[] contentArray = new Object[]{SystemNameEnum.SYS_NAME_CN.value(), receiver,
                emailCode, Constant.EMAIL_CODEVALIDATE, SystemNameEnum.SYS_NAME_CN.value(), simpleDateFormat.format(new Date())};
        String content = MessageFormat.format(sysMsgSendWayEntity.getMsgTemplateContent(), contentArray);
        try {
            f = emailUtils.sendMailByLogin(receiver, title, content);
            if (f) {
                SysEmailContentEntity emailContent = sysEmailContentService.getByEmail(receiver);
                String emailValidateTime = Constant.EMAIL_CODEVALIDATE;
                if (emailValidateTime == null || emailValidateTime.length() == 0 || emailValidateTime.equals("0")) {
                    emailValidateTime = "20";
                }
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MINUTE, Integer.parseInt(emailValidateTime));
                if (emailContent == null) {
                    SysEmailContentEntity sysEmailContentEntity = new SysEmailContentEntity();
                    sysEmailContentEntity.setEmail(receiver);
                    sysEmailContentEntity.setEmailExpiresAt(calendar.getTime());
                    sysEmailContentEntity.setEmailCode(emailCode);
                    sysEmailContentService.saveEmail(sysEmailContentEntity);
                } else {
                    emailContent.setEmailExpiresAt(calendar.getTime());
                    emailContent.setEmailCode(emailCode);
                    sysEmailContentService.updateEmailCode(emailContent);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendEmailByRest(String receiver) {
        boolean f = false;
        String emailCode = generateVerCode();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 获取消息发送的方并填入值
        SysMsgSendWayEntity sysMsgSendWayEntity = sysMsgSendWayService.selectBySendTypeAndType(MsgSendWayTypeEnum.
                MAIL.value(), MsgTypeEnum.EMAIL_RESET_CODE.value());
        Object[] titleArray = new Object[]{SystemNameEnum.SYS_NAME_CN.value()};
        String title = MessageFormat.format(sysMsgSendWayEntity.getMsgTemplateTitle(), titleArray);
        Object[] contentArray = new Object[]{SystemNameEnum.SYS_NAME_CN.value(), receiver,
                emailCode, Constant.EMAIL_CODEVALIDATE, SystemNameEnum.SYS_NAME_CN.value(), simpleDateFormat.format(new Date())};
        String content = MessageFormat.format(sysMsgSendWayEntity.getMsgTemplateContent(), contentArray);
        try {
            f = emailUtils.sendMailByLogin(receiver, title, content);
            if (f) {
                SysEmailContentEntity emailContent = sysEmailContentService.getByEmail(receiver);
                String emailValidateTime = Constant.EMAIL_CODEVALIDATE;
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MINUTE, Integer.parseInt(emailValidateTime));
                if (emailContent == null) {
                    SysEmailContentEntity sysEmailContentEntity = new SysEmailContentEntity();
                    sysEmailContentEntity.setEmail(receiver);
                    sysEmailContentEntity.setEmailExpiresAt(calendar.getTime());
                    sysEmailContentEntity.setEmailCode(emailCode);
                    sysEmailContentService.saveEmail(sysEmailContentEntity);
                } else {
                    emailContent.setEmailExpiresAt(calendar.getTime());
                    emailContent.setEmailCode(emailCode);
                    sysEmailContentService.updateEmailCode(emailContent);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendEmailByEmail(String receiver) {
        boolean f = false;
        String emailCode = generateVerCode();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 获取消息发送的方并填入值
        SysMsgSendWayEntity sysMsgSendWayEntity = sysMsgSendWayService.selectBySendTypeAndType(MsgSendWayTypeEnum.
                MAIL.value(), MsgTypeEnum.EMAIL_FIRST_CODE.value());
        Object[] titleArray = new Object[]{SystemNameEnum.SYS_NAME_CN.value()};
        String title = MessageFormat.format(sysMsgSendWayEntity.getMsgTemplateTitle(), titleArray);
        Object[] contentArray = new Object[]{SystemNameEnum.SYS_NAME_CN.value(), receiver,
                emailCode, Constant.EMAIL_CODEVALIDATE, SystemNameEnum.SYS_NAME_CN.value(), simpleDateFormat.format(new Date())};
        String content = MessageFormat.format(sysMsgSendWayEntity.getMsgTemplateContent(), contentArray);
        try {
            f = emailUtils.sendMailByLogin(receiver, title, content);
            if (f) {
                SysEmailContentEntity emailContent = sysEmailContentService.getByEmail(receiver);
                String emailValidateTime = Constant.EMAIL_CODEVALIDATE;
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MINUTE, Integer.parseInt(emailValidateTime));
                if (emailContent == null) {
                    SysEmailContentEntity sysEmailContentEntity = new SysEmailContentEntity();
                    sysEmailContentEntity.setEmail(receiver);
                    sysEmailContentEntity.setEmailExpiresAt(calendar.getTime());
                    sysEmailContentEntity.setEmailCode(emailCode);
                    sysEmailContentService.saveEmail(sysEmailContentEntity);
                } else {
                    emailContent.setEmailExpiresAt(calendar.getTime());
                    emailContent.setEmailCode(emailCode);
                    sysEmailContentService.updateEmailCode(emailContent);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendEmailByNewEmail(String receiver,String username) {
        boolean f = false;
        String emailCode = generateVerCode();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 获取消息发送的方并填入值
        SysMsgSendWayEntity sysMsgSendWayEntity = sysMsgSendWayService.selectBySendTypeAndType(MsgSendWayTypeEnum.
                MAIL.value(), MsgTypeEnum.EMAIL_CHANGE_CODE.value());
        Object[] titleArray = new Object[]{SystemNameEnum.SYS_NAME_CN.value()};
        String title = MessageFormat.format(sysMsgSendWayEntity.getMsgTemplateTitle(), titleArray);
        Object[] contentArray = new Object[]{SystemNameEnum.SYS_NAME_CN.value(), username,
                emailCode, Constant.EMAIL_CODEVALIDATE, SystemNameEnum.SYS_NAME_CN.value(), simpleDateFormat.format(new Date())};
        String content = MessageFormat.format(sysMsgSendWayEntity.getMsgTemplateContent(), contentArray);
        try {
            f = emailUtils.sendMailByLogin(receiver, title, content);
            if (f) {
                SysEmailContentEntity emailContent = sysEmailContentService.getByEmail(receiver);
                String emailValidateTime = Constant.EMAIL_CODEVALIDATE;
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MINUTE, Integer.parseInt(emailValidateTime));
                if (emailContent == null) {
                    SysEmailContentEntity sysEmailContentEntity = new SysEmailContentEntity();
                    sysEmailContentEntity.setEmail(receiver);
                    sysEmailContentEntity.setEmailExpiresAt(calendar.getTime());
                    sysEmailContentEntity.setEmailCode(emailCode);
                    sysEmailContentService.saveEmail(sysEmailContentEntity);
                } else {
                    emailContent.setEmailExpiresAt(calendar.getTime());
                    emailContent.setEmailCode(emailCode);
                    sysEmailContentService.updateEmailCode(emailContent);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendEmailByAppeal(AppealDTO appealDTO, String admineMail) {
        boolean f = false;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SysMsgSendWayEntity sysMsgSendWayEntityByEmail = sysMsgSendWayService.selectBySendTypeAndType(MsgSendWayTypeEnum.
                MAIL.value(), MsgTypeEnum.PASSWORD_REST_CODE.value());
        Object[] contentArrayEmail = new Object[]{appealDTO.getCompName(), appealDTO.getCompName(), appealDTO.getAcount(),
                appealDTO.getCompMobile(), appealDTO.getCompEmail(), appealDTO.getCompMemo(), appealDTO.getSelfMobile(), appealDTO.getSelfEmail(), SystemNameEnum.SYS_NAME_CN.value(), simpleDateFormat.format(new Date())};
        String contentEmail = MessageFormat.format(sysMsgSendWayEntityByEmail.getMsgTemplateContent(), contentArrayEmail);
        Object[] titleArrayEmail = new Object[]{SystemNameEnum.SYS_NAME_CN.value()};
        String titleEmail = MessageFormat.format(sysMsgSendWayEntityByEmail.getMsgTemplateTitle(), titleArrayEmail);
        try {
            f = emailUtils.sendMailByLogin(admineMail, titleEmail, contentEmail);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendEmailByUserEmpl(String receiver, String compName, String userInfo) {
        boolean f = false;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SysMsgSendWayEntity sysMsgSendWayEntityByEmail = sysMsgSendWayService.selectBySendTypeAndType(MsgSendWayTypeEnum.
                MAIL.value(), MsgTypeEnum.EMPL_JOIN_APPL.value());
        Object[] contentArrayEmail = new Object[]{compName, userInfo, SystemNameEnum.SYS_NAME_CN.value(), simpleDateFormat.format(new Date())};
        String contentEmail = MessageFormat.format(sysMsgSendWayEntityByEmail.getMsgTemplateContent(), contentArrayEmail);
        Object[] titleArrayEmail = new Object[]{SystemNameEnum.SYS_NAME_CN.value()};
        String titleEmail = MessageFormat.format(sysMsgSendWayEntityByEmail.getMsgTemplateTitle(), titleArrayEmail);
        try {
            f = emailUtils.sendMailByLogin(receiver, titleEmail, contentEmail);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendEmailByManager(String receiver, String compName, String decision) {
        boolean f = false;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SysMsgSendWayEntity sysMsgSendWayEntityByEmail = sysMsgSendWayService.selectBySendTypeAndType(MsgSendWayTypeEnum.
                MAIL.value(), MsgTypeEnum.MANAGER_AGREE_REFUSE.value());
        Object[] contentArrayEmail = new Object[]{SystemNameEnum.SYS_NAME_CN.value(), compName, decision, SystemNameEnum.SYS_NAME_CN.value(), simpleDateFormat.format(new Date())};
        String contentEmail = MessageFormat.format(sysMsgSendWayEntityByEmail.getMsgTemplateContent(), contentArrayEmail);
        Object[] titleArrayEmail = new Object[]{SystemNameEnum.SYS_NAME_CN.value()};
        String titleEmail = MessageFormat.format(sysMsgSendWayEntityByEmail.getMsgTemplateTitle(), titleArrayEmail);
        try {
            f = emailUtils.sendMailByLogin(receiver, titleEmail, contentEmail);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }

    /**
     * 待定 邮箱注册
     *
     * @param
     * @return
     * @author Dingyayong
     * @date 2019/12/6 9:11
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendEmailByRegister(String receiver) {
        return false;
    }

    /**
     * 出差/差旅/借款发送邮件
     * @author Dingyayong
     * @date 2019/12/14
     * @param email eamil地址
     * @param emailTitle email标题
     * @param emailContent 内容
     */
    @Override
    public void sendEmailByTrvl(String email, String emailTitle, String emailContent) {
        try {
            emailUtils.sendMailByLogin(email, emailTitle, emailContent);
        } catch (Exception e) {
            throw new RenException(ErrorCode.EMAIL_FAIL_SEND);
        }
    }
}
